﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

using SsrsRenderStudio.Wcf;
using System.Configuration;

namespace SsrsRenderStudio.Wcf.Host
{
    public class CustomServiceHost : ServiceHost
    {
        public bool IsValidInstance = false;
        public string LastException = "";

        public CustomServiceHost(Type serviceType) : base(serviceType) 
        {
           
        }
   
        protected override void ApplyConfiguration()
        {
            IsValidInstance = configureService();
        }
        
        private bool configureService() 
        {   
            string configurationFilePath = string.Empty;

            try
            {
                WcfConfiguration.FetchNextBindingConfiguration(base.Description.ServiceType, out configurationFilePath);
                if (string.IsNullOrEmpty(configurationFilePath)) return false;
                return configureServiceSection(configurationFilePath);
            }
            catch (Exception ex)
            {
                LastException = ex.Message;
                return false;
            }
        }

        private bool configureServiceSection(string configurationFilePath)
        {
            ExeConfigurationFileMap filemap = new ExeConfigurationFileMap();
            filemap.ExeConfigFilename = configurationFilePath;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
            System.ServiceModel.Configuration.ServiceModelSectionGroup serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);

            foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)
            {
                if (se.Name == this.Description.ConfigurationName)
                {
                    base.LoadConfigurationSection(se);
                    return true;
                }
            }

            return false;
        }
    }
}
